package cn.yulezhisi.shiro.realms;

import cn.yulezhisi.common.util.Log;
import cn.yulezhisi.entity.SysRole;
import cn.yulezhisi.entity.SysUser;
import cn.yulezhisi.service.SysRoleService;
import cn.yulezhisi.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author yulezhisi
 **/

public class ShiroRealm extends AuthorizingRealm{
    
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private SysRoleService sysRoleService;
    
    /**
     * 被shiro回调方法  用于登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        
        Log.logger.info(username + "");
        // 根据用户名查找用户创建一个认证信息
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        SysUser user = sysUserService.queryOne(sysUser);
        
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,
                                                                                   user.getPassword(),
                                                                                   getName());
        Log.logger.info(authenticationInfo + "");
        return authenticationInfo;
    }
    
    /**
     * 被shiro回调 用于权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        
        //1. 获取登录用户的信息  多realm存放的principal 是一个linkedList  和配置顺序有关
        SysUser user = (SysUser) principals.getPrimaryPrincipal();
        
        Log.logger.info("进入授权" + ":" + user);
        
        //2. 使用用户信息获取当前用户 角色或者权限, 可能需要查数据库
        //从数据库获取用户角色
        List<SysRole> roles = sysRoleService.listRoleByUserId(user.getId());
        
        
        
        //3. 返回 授权对象 并设置roles,permission
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        
        return authorizationInfo;
    }
}



















